package com.fucking.great.context.plun;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.system.SystemUtil;
import com.fucking.great.context.TxnContext;
import com.fucking.great.context.common.CallService;
import com.fucking.great.context.engine.GroovyClassLoaderEngine;
import com.fucking.great.context.manager.PlugManager;
import com.fucking.great.context.util.GetMapDecorator;
import com.fucking.great.context.util.SingleUtil;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 该CallService是从单例工具类中获得的。
 * 如果需要扩展无状态的，可以从单例中扩展出来。
 * @see CallService
 */
public class LoggerPlug extends BasePlug{
    public static final String PLUN_NAME = "logger";
    public static final String LOGGER_PLUG_FORMAT = "LOGGER_PLUG_FORMAT";
    public static final String FORMAT = SystemUtil.get(LOGGER_PLUG_FORMAT, "{path}.{type}.{systemName}.{appid}.{locale}");

    public LoggerPlug(Map<String, String> config) {
        super( config,new String[]{
                Log.class.getName()
        });
    }
    public static final Log logger = LogFactory.get();
    @Override
    protected void initUserPlunMap(Map<String, Object> userPlun) {
        // 获得组装的名称.
        TxnContext txnContext = TxnContext.getContext();
        String path = txnContext.getPath();
        String systemName = txnContext.getSystemName();
        String appid = txnContext.getAppid();
        String type = txnContext.getType();
        Locale locale = txnContext.getLocale();
        //
        Map<String,String> formatMap = new HashMap<>(5);
        formatMap.put("path",path);
        formatMap.put("systemName",systemName);
        formatMap.put("appid",appid);
        formatMap.put("type",type);
        // 这里设置国家.
        formatMap.put("locale",locale.toString());

        // 设置日志名：
        String logName = StrUtil.format(FORMAT);
        logName = logName.toLowerCase();
        // 替换特殊字符
        logName = StrUtil.replaceChars(logName , new char[]{ '/' , '\\' , '_'  } , ".");
        //
        Log log = LogFactory.get(logName);
        userPlun.put(PLUN_NAME, log);
    }

    /**
     * 追加 '.'
     * @param sb
     */
    private void appDot(StringBuilder sb) {
        sb.append('.');
    }

}
